package cn.iocoder.yudao.module.erp.controller.admin.gi.giyw;

import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;
import javax.validation.*;
import javax.servlet.http.*;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.util.*;
import java.io.IOException;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import cn.iocoder.yudao.module.erp.controller.admin.gi.giyw.vo.*;
import cn.iocoder.yudao.module.erp.dal.dataobject.gi.GiYwDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.giitem.GiItemYwDO;
import cn.iocoder.yudao.module.erp.service.gi.GiYwService;
import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.*;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;


@Tag(name = "管理后台 - ERP物流义乌仓库")
@RestController
@RequestMapping("/erp/gi-yw")
@Validated
public class GiYwController {

    @Resource
    private GiYwService giYwService;

    @PostMapping("/create")
    @Operation(summary = "创建ERP物流义乌仓库")
//    @PreAuthorize("@ss.hasPermission('erp:gi-yw:create')")
    public CommonResult<String> createGiYw(@Valid @RequestBody GiYwSaveReqVO createReqVO) {
        return success(giYwService.createGiYw(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新ERP物流义乌仓库")
//    @PreAuthorize("@ss.hasPermission('erp:gi-yw:update')")
    public CommonResult<Boolean> updateGiYw(@Valid @RequestBody GiYwSaveReqVO updateReqVO) {
        giYwService.updateGiYw(updateReqVO);
        return success(true);
    }

    @PutMapping("/examine")
    @Operation(summary = "ERP物流义乌仓库单据审核")
//    @PreAuthorize("@ss.hasPermission('erp:gi-yw:examine')")
    public CommonResult<Boolean> examineGiYw(@Valid @RequestBody GiYwDO giYwDO) {
        giYwService.examineGiYw(giYwDO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除ERP物流义乌仓库")
    @Parameter(name = "id", description = "编号", required = true)
//    @PreAuthorize("@ss.hasPermission('erp:gi-yw:delete')")
    public CommonResult<Boolean> deleteGiYw(@RequestParam("id") String id) {
        giYwService.deleteGiYw(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得ERP物流义乌仓库")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
//    @PreAuthorize("@ss.hasPermission('erp:gi-yw:query')")
    public CommonResult<GiYwRespVO> getGiYw(@RequestParam("id") String id) {
        GiYwDO giYw = giYwService.getGiYw(id);
        return success(BeanUtils.toBean(giYw, GiYwRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得ERP物流义乌仓库分页")
//    @PreAuthorize("@ss.hasPermission('erp:gi-yw:query')")
    public CommonResult<PageResult<GiYwRespVO>> getGiYwPage(@Valid GiYwPageReqVO pageReqVO) {
        //现暂不需分页
        pageReqVO.setPageSize(-1);
        PageResult<GiYwDO> pageResult = giYwService.getGiYwPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, GiYwRespVO.class));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出ERP物流义乌仓库 Excel")
//    @PreAuthorize("@ss.hasPermission('erp:gi-yw:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportGiYwExcel(@Valid GiYwPageReqVO pageReqVO,
                                HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<GiYwDO> list = giYwService.getGiYwPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "ERP物流义乌仓库.xls", "数据", GiYwRespVO.class,
                BeanUtils.toBean(list, GiYwRespVO.class));
    }

//    @GetMapping("/export-excel")
//    @Operation(summary = "导出ERP物流义乌仓库 Excel")
//    @PreAuthorize("@ss.hasPermission('erp:gi-yw:export')")
//    @ApiAccessLog(operateType = EXPORT)
//    public void exportGiYwExcel(@Valid GiYwPageReqVO pageReqVO,
//                                HttpServletResponse response) throws IOException {
//        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
//        List<GiYwDO> list = giYwService.getGiYwPage(pageReqVO).getList();
//
//        ObjectMapper objectMapper = new ObjectMapper();
//        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//
//        // 创建 Excel 工作簿和表单
//        Workbook workbook = new XSSFWorkbook();
//        Sheet sheet = workbook.createSheet("数据");
//        sheet.addMergedRegion(new CellRangeAddress(0, 0, 11, 13));
//
//        // 设置标题行
//        String[] headers = {"运单号ID", "货号", "仓库类型", "入库件数", "入库品名", "入库体积", "重量", "密度",
//                "送货人联系方式", "送货人名称", "垫付金额", "入库照片", "","","线路选择", "创建者", "订单时间", "附件", "备注", "状态", "出入库状态"};
//        Row headerRow = sheet.createRow(0);
//        for (int i = 0; i < headers.length; i++) {
//            headerRow.createCell(i).setCellValue(headers[i]);
//        }
//
//        int rowIdx = 1;
//        for (GiYwDO item : list) {
//            Row row = sheet.createRow(rowIdx);
//            // 设置普通字段的值
//            row.createCell(0).setCellValue(item.getId());
//            row.createCell(1).setCellValue(item.getNo());
//            row.createCell(2).setCellValue(item.getStoreType() != null ? item.getStoreType().toString() : "");
//            row.createCell(3).setCellValue(item.getInCount() != null ? item.getInCount().toString() : "");
//            row.createCell(4).setCellValue(item.getInName());
//            row.createCell(5).setCellValue(item.getInVolume() != null ? item.getInVolume().toString() : "");
//            row.createCell(6).setCellValue(item.getWeight() != null ? item.getWeight().toString() : "");
//            row.createCell(7).setCellValue(item.getDensity() != null ? item.getDensity().toString() : "");
//            row.createCell(8).setCellValue(item.getDeliveryPhone());
//            row.createCell(9).setCellValue(item.getDeliveryName());
//            row.createCell(10).setCellValue(item.getEarpayAmount() != null ? item.getEarpayAmount().toString() : "");
//            // 解析 `inPic` 的 JSON 字符串并插入图片
//            String imageJson = item.getInPic();
//            if (imageJson != null && !imageJson.isEmpty()) {
//                try {
//                    List<Map<String, String>> imageInfos = objectMapper.readValue(imageJson, new TypeReference<List<Map<String, String>>>() {});
//                    int colIdx = 11; // 图片列起始索引
//                    for (Map<String, String> imageInfo : imageInfos) {
//                        String imageUrl = imageInfo.get("url");
//                        byte[] imageBytes = downloadImage(imageUrl);
//                        if (imageBytes != null) {
//                            int pictureIdx = workbook.addPicture(imageBytes, Workbook.PICTURE_TYPE_PNG);
//                            Drawing<?> drawing = sheet.createDrawingPatriarch();
//                            CreationHelper helper = workbook.getCreationHelper();
//                            ClientAnchor anchor = helper.createClientAnchor();
//                            anchor.setAnchorType(AnchorType.MOVE_AND_RESIZE);
//                            anchor.setCol1(colIdx++);
//                            anchor.setRow1(rowIdx);
//                            Picture picture = drawing.createPicture(anchor, pictureIdx);
//                            picture.resize(0.5); // 调整图片大小适应单元格
//                        }
//                    }
//                    // 合并单元格
//                    if (imageInfos.size() > 1) {
//                            sheet.addMergedRegion(new CellRangeAddress(rowIdx, rowIdx, 11, colIdx - 1));
//                    }
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//            row.createCell(14).setCellValue(item.getLine() != null ? item.getLine().toString() : "");
//            row.createCell(15).setCellValue(item.getCreator());
//            // 处理订单时间，检查数组的长度并格式化日期
//            LocalDateTime createTime = item.getCreateTime();
//            if (createTime != null) {
//                row.createCell(16).setCellValue(formatter.format(createTime));
//            } else {
//                row.createCell(16).setCellValue("");
//            }
//            row.createCell(17).setCellValue(item.getFile());
//            row.createCell(18).setCellValue(item.getNote());
//            row.createCell(19).setCellValue(item.getStatus() != null ? item.getStatus().toString() : "");
//            row.createCell(20).setCellValue(item.getInventoryStatus() != null ? item.getInventoryStatus().toString() : "");
//            rowIdx++;
//        }
//        // 导出 Excel
//        // 设置响应头信息并写入 Excel 文件
//        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//        response.setHeader("Content-Disposition", "attachment; filename=ERP物流义乌仓库.xlsx");
//        workbook.write(response.getOutputStream());
//        workbook.close();
//    }

    // 下载图片的辅助方法，兼容 Java 8
    private byte[] downloadImage(String imageUrl) {
        try (InputStream inputStream = new URL(imageUrl).openStream();
             ByteArrayOutputStream buffer = new ByteArrayOutputStream()) {

            int bytesRead;
            byte[] data = new byte[1024];
            while ((bytesRead = inputStream.read(data, 0, data.length)) != -1) {
                buffer.write(data, 0, bytesRead);
            }
            return buffer.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    // ==================== 子表（ERP物流义乌仓库货号详情） ====================

    @GetMapping("/gi-item-yw/list-by-no")
    @Operation(summary = "获得ERP物流义乌仓库货号详情列表")
    @Parameter(name = "no", description = "入库编号")
//    @PreAuthorize("@ss.hasPermission('erp:gi-yw:detail')")
    public CommonResult<List<GiItemYwDO>> getGiItemYwListByNo(@RequestParam("no") String no) {
        return success(giYwService.getGiItemYwListByNo(no));
    }

}